﻿using System;
using System.Web.Security;

namespace rpxnow_library.membership
{
    /// <summary>
    /// Utilities for the entire solution to use.
    /// </summary>
    internal static class Utils
    {
        /// <summary>
        /// Loads the data context for the LinqToSql
        /// </summary>
        /// <param name="connectionString"></param>
        /// <returns></returns>
        static public rpxnow_library.membership.data.Context LoadDataContext(string connectionString)
        {
            if (string.IsNullOrEmpty(connectionString))
                throw new ArgumentNullException("connectionString");

            return new data.Context(connectionString);
        }

        /// <summary>
        /// queries the web.config for the connections string witht the given connection name
        /// </summary>
        /// <param name="connectionStringName"></param>
        /// <returns></returns>
        static public string GetConnectionStringFromName(string connectionStringName)
        {
            try
            {
                return System.Web.Configuration.WebConfigurationManager.ConnectionStrings[connectionStringName].ConnectionString;
            }
            catch (Exception)
            {
            }
            return string.Empty;
        }

        /// <summary>
        /// Throws an exception if excessive attributes remain
        /// </summary>
        /// <param name="config"></param>
        static public void HandleExcessAttributes(System.Collections.Specialized.NameValueCollection config)
        {
            if (config.Count > 0)
            {
                string attr = config.GetKey(0);
                if (!string.IsNullOrEmpty(attr))
                    throw new System.Configuration.Provider.ProviderException("Unrecognized attribute: " + attr);
            }
        }

        /// <summary>
        /// Returns the parameter value for a given parameter name
        /// </summary>
        /// <param name="config"></param>
        /// <param name="parameterName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        static public string GetInitializationConfigParameter(System.Collections.Specialized.NameValueCollection config, string parameterName, string defaultValue)
        {
            string value = string.Empty;

            if (config[parameterName] == null)
            {
                config[parameterName] = defaultValue;
            }
            value = config[parameterName];
            config.Remove(parameterName);

            return value;
        }
    }
}
